using System;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using ConfigurationManager=InfiniTec.Configuration.ConfigurationManager;

namespace InfiniTec
{
    public class ConnectionStringNameConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string name = (string) value;
            if (string.IsNullOrEmpty(name)) return null;

            return System.Configuration.ConfigurationManager.ConnectionStrings[name];
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
                                         Type destinationType)
        {
            return (value == null) ? string.Empty : ((ConnectionStringSettings) value).Name;
        }
    }
}